import React, { useState, useEffect, useRef } from "react";
import { Row, Col, Card } from "antd";
import VisitorMonitor from "./Cockpitpages/VisitorMonitor";
import IndustryDistribution from "./Cockpitpages/IndustryDistribution";
import PropertyFee from "./Cockpitpages/PropertyFee";
import IncomeTrend from "./Cockpitpages/IncomeTrend";
import EnergyRanking from "./Cockpitpages/EnergyRanking";
import "../visualFilecss/VisualCockpit.css";
import axios from "axios";

const CARD_STYLE = {
  border: "1px solid rgba(97, 168, 219, 0.8)",
  background: "rgba(9, 27, 55, 0.2)",
  marginBottom: 16,
  overflow: "hidden",
  borderRadius: 10,
  boxSizing: "border-box",
};
const CARD_STYLE2 = {
  background: "rgba(9, 27, 55, 0)",
  marginBottom: 16,
  overflow: "hidden",
  borderRadius: 10,
  boxSizing: "border-box",
};

const MAX_RECONNECT_ATTEMPTS = 3;
const RECONNECT_INTERVAL = 5000; // 5秒

export default function VisualCockpit() {
  

  const [mongoData, setMongoData] = useState({});
  const wsRef = useRef(null);
  const lastPingTimeRef = useRef(Date.now());
  const heartbeatTimeoutRef = useRef(null);
  const reconnectAttemptsRef = useRef(0);
  const reconnectTimeoutRef = useRef(null);

  const connectWebSocket = () => {
    const ws = new window.WebSocket("ws://localhost:3005");
    wsRef.current = ws;

    const closeWS = () => {
      if (wsRef.current && wsRef.current.readyState === 1) {
        wsRef.current.close();
      }
    };

    const resetHeartbeatTimeout = () => {
      if (heartbeatTimeoutRef.current) clearTimeout(heartbeatTimeoutRef.current);
      heartbeatTimeoutRef.current = setTimeout(() => {
        console.warn("5秒未收到服务器ping，断开连接");
        closeWS();
      }, 5000);
    };

    ws.onopen = () => {
      console.log("WebSocket 连接已建立");
      reconnectAttemptsRef.current = 0; // 重连成功，重置计数
      resetHeartbeatTimeout();
    };

    ws.onmessage = (event) => {
      try {
        const msg = JSON.parse(event.data);
        if (msg.type === "welcome" || msg.type === "data_update") {
          setMongoData(Array.isArray(msg.data) ? msg.data[0] : msg.data);
          console.log("收到后端推送数据");
        } else if (msg.type === "ping") {
          ws.send(JSON.stringify({ type: "pong" }));
          lastPingTimeRef.current = Date.now();
          resetHeartbeatTimeout();
        }
      } catch (e) {
        console.error("WebSocket 消息解析失败", e);
      }
    };

    ws.onclose = () => {
      console.log("WebSocket 连接已关闭");
      if (heartbeatTimeoutRef.current) clearTimeout(heartbeatTimeoutRef.current);
      // 断线重连逻辑
      if (reconnectAttemptsRef.current < MAX_RECONNECT_ATTEMPTS) {
        reconnectAttemptsRef.current += 1;
        console.warn(`WebSocket 断开，${RECONNECT_INTERVAL / 1000}秒后第${reconnectAttemptsRef.current}次重连...`);
        reconnectTimeoutRef.current = setTimeout(() => {
          connectWebSocket();
        }, RECONNECT_INTERVAL);
      } else {
        console.error("WebSocket 重连超过最大次数，已放弃重连。");
      }
    };

    ws.onerror = (err) => {
      if (wsRef.current === WebSocket.CLOSED) {
        console.error("WebSocket 发生错误", err);
        wsRef.current.close();
      }
    };
  };

  useEffect(() => {
    connectWebSocket();
    return () => {
      if (heartbeatTimeoutRef.current) clearTimeout(heartbeatTimeoutRef.current);
      if (reconnectTimeoutRef.current) clearTimeout(reconnectTimeoutRef.current);
      if (wsRef.current) wsRef.current.close();
    };
  }, []);

  useEffect(() => {
    if (
      mongoData &&
      (Array.isArray(mongoData)
        ? mongoData.length > 0
        : Object.keys(mongoData).length > 0)
    ) {
      // console.log("mongoData已更新：", mongoData);
      console.log("mongoData已更新");
    }
  }, [mongoData]);

  return (
    <div className="visualCockpit" style={{ minHeight: "100%", padding: 16 }}>
      <Row gutter={20}>
        {/* 左侧栏 */}
        <Col span={8} style={{ height: 660 }}>
          <Card bordered={false} style={{ height: 300, ...CARD_STYLE }}>
            <div style={{ height: 228 }}>
              <VisitorMonitor data={mongoData.visitorData} />
            </div>
          </Card>
          <Card bordered={false} style={{ height: 345, ...CARD_STYLE }}>
            <div style={{ height: 360 }}>
              <IndustryDistribution data={mongoData.industryData} />
            </div>
          </Card>
        </Col>
        {/* 中间栏 */}
        <Col
          span={8}
          style={{
            border: "1px solid rgba(97, 168, 219, 0.8)",
            height: 660,
            borderRadius: 10,
            background: "rgba(9, 27, 55, 0.2)",
          }}
        >
          <Card
            bordered={false}
            style={{
              height: 300,
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
              ...CARD_STYLE2,
            }}
          >
            <div
              style={{
                height: 108,
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <div
                style={{ fontSize: 32, color: "#00eaff", fontWeight: "bold" }}
              >
                当前园区总收入：
              </div>
              <div
                style={{ fontSize: 48, color: "#00eaff", fontWeight: "bold" }}
              >
                15,092,346 <span style={{ fontSize: 24 }}>元</span>
              </div>
            </div>
          </Card>
          <Card
            bordered={false}
            style={{ height: 330, marginBottom: 0, ...CARD_STYLE2 }}
          >
            <div style={{ height: 330 }}>
              <IncomeTrend data={mongoData.incomeTrendData} />
            </div>
          </Card>
        </Col>
        {/* 右侧栏 */}
        <Col span={8} style={{ height: 660 }}>
          <Card bordered={false} style={{ height: 300, ...CARD_STYLE }}>
            <div style={{ height: 300 }}>
              <EnergyRanking data={mongoData.energyRankingData} />
            </div>
          </Card>
          <Card bordered={false} style={{ height: 345, ...CARD_STYLE }}>
            <div style={{ height: 148 }}>
              <PropertyFee data={mongoData.propertyFeeData} />
            </div>
          </Card>
          {/* <Card bordered={false} style={{  height: 220, marginBottom: 0 }}>
            <div style={{ height: 188 }}><DeviceFault data={deviceFaultData} /></div>
          </Card> */}
        </Col>
      </Row>
    </div>
  );
}
